<template>
  <div id="mapView" class="relative">
    <!-- <div class="mapList" v-show="current == 'toggle'">
      <scroll-bar style="width:250px; height:550px;color:#fff">
        <div id="basemapGallery"></div>
      </scroll-bar>
    </div> -->
    <!-- <div class="mapList measure" v-show="current == 'distance'">
      <div id="measurementDiv"></div>
    </div>
    <div id="search"></div> -->
  </div>
</template>
<script>
/* eslint-disable */
import { loadModules } from 'esri-loader'

import proj4 from 'proj4'
proj4.defs([
  ['EPSG:30007', '+proj=tmerc +lat_0=0 +lon_0=118.5 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'],
  ['EPSG:4548', '+proj=tmerc +lat_0=0 +lon_0=117 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'],
  ['EPSG:4490', '+proj=longlat +ellps=GRS80 +no_defs']
])
export default {
  name: 'mapview',
  props: {
    current: {
      type: String,
      default: ''
    },
    dataSources: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      map: null,
      dischargeOutlets: [],
      geometryServiceURL: 'http://192.168.20.156:6080/arcgis/rest/services/Utilities/Geometry/GeometryServer'
    }
  },
  created() {},
  mounted() {
    console.log('map')
    //this.initMap();
    this.testTDT()
  },
  methods: {
    initMap() {
      //这里可以使用自己的地址
      const options = {
        url: 'https://js.arcgis.com/3.34/',
        dojoConfig: {
          async: true,
          packages: [
            {
              location: '/modules',
              name: 'modules'
            }
          ]
        }
      }
      loadModules(
        [
          'esri/map',
          'modules/TDTLayerC',
          'esri/layers/WebTiledLayer',
          'esri/layers/ArcGISDynamicMapServiceLayer',
          'esri/SpatialReference',
          'esri/geometry/Extent',
          'esri/geometry/Point',
          'esri/graphic',
          'esri/layers/GraphicsLayer',
          'esri/symbols/PictureMarkerSymbol',
          'esri/tasks/GeometryService',
          'esri/tasks/ProjectParameters',
          'dojo/on',
          'dojo/dom',
          'dojo/domReady!'
        ],
        options
      )
        .then(
          ([
            Map,
            TDTLayer,
            WebTiledLayer,
            ArcGISDynamicMapServiceLayer,
            SpatialReference,
            Extent,
            Point,
            Graphic,
            GraphicsLayer,
            PictureMarkerSymbol,
            GeometryService,
            ProjectParameters,
            on,
            dom
          ]) => {
            this.map = new Map('mapView', { logo: false })
            this.map.setMapCursor('pointer') //设置鼠标在map上时的样式为手型
            this.spatialReference = new SpatialReference({
              wkt: 'PROJCS["CGCS2000_3_Degree_GK_CM_117E",GEOGCS["GCS_China_Geodetic_Coordinate_System_2000",DATUM["D_China_2000",SPHEROID["CGCS2000",6378137.0,298.257222101]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Gauss_Kruger"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",118.5],PARAMETER["Scale_Factor",1.0],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]'
            })
            this.mapDef = new Promise((resolve, reject) => {
              try {
                this.map.on('load', (res) => {
                  resolve(res)
                })
              } catch (err) {
                reject(err)
              }
            })
            this.geometryService = new GeometryService(this.geometryServiceURL)
            Promise.all([this.mapDef, this.queryDef]).then((response) => {
              console.log(response)
              let res = response[1]
              let dischargeOutlets = res.data.dischargeOutlets
              let geometries = []
              var webMercator =
                '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs'
              var cgcs30007 = '+proj=tmerc +lat_0=0 +lon_0=118.5 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
              var pmSymbol = new PictureMarkerSymbol({
                url: require('@/assets/map/point.png'),
                height: 10,
                width: 10
              })
              dischargeOutlets.map((item, index) => {
                if (!isNaN(Number(item.coordinateY)) && !isNaN(Number(item.coordinateX)) && index < 5000) {
                  let lnglat = proj4(cgcs30007, webMercator, [Number(item.coordinateY), Number(item.coordinateX)])
                  let pt = new Point(lnglat[0], lnglat[1], this.spatialReference)
                  let graphic = new Graphic(pt, pmSymbol)
                  this.graphicLayer.add(graphic)
                }
              })

              // var params = new ProjectParameters();
              // params.geometries = geometries;
              // params.outSR = new SpatialReference({
              //   wkid:3857
              // });
              // this.geometryService.project(params,outGeometries =>{
              //   console.log(outGeometries)
              //   outGeometries.map(geometry => {
              //     var pmSymbol = new PictureMarkerSymbol({
              //       url: require('@/assets/map/icon_znjg.png'),
              //       height: 10,
              //       width: 10,
              //     })
              //     let graphic = new Graphic(geometry, pmSymbol);
              //     this.graphicLayer.add(graphic);
              //   })

              // }, err =>{
              //   console.log(err)
              // });
            })
            //底图切换
            this.tdtImgLayer = new WebTiledLayer(
              'http://${subDomain}.tianditu.gov.cn/img_w/wmts?tk=e7a4ecf4e9b91b917bc4a597c517bfba&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}',
              {
                subDomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
              }
            )
            this.map.addLayer(this.tdtImgLayer)
            this.tdtImgLayer.hide()

            // this.initialExtent = new Extent(5916776.8, 1877209.3, 19242502.6, 7620381.8, this.map.spatialReference);
            this.initialExtent = new Extent(
              13180709.813449485,
              2855211.6152346493,
              13227795.02287309,
              2875199.898131196,
              this.map.spatialReference
            )
            this.map.setExtent(this.initialExtent)

            this.tdtVecLayer = new WebTiledLayer(
              'http://${subDomain}.tianditu.gov.cn/vec_w/wmts?tk=e7a4ecf4e9b91b917bc4a597c517bfba&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL=${col}&TILEROW=${row}&TILEMATRIX=${level}',
              {
                subDomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
              }
            )

            this.map.addLayer(this.tdtVecLayer)
          }
        )
        .catch((err) => {
          // console.log(err);
          this.$message.error('arcgis 加载出错')
        })
    },
    testTDT() {
      //这里可以使用自己的地址
      const options = {
        url: 'https://js.arcgis.com/3.34/',
        dojoConfig: {
          async: true,
          packages: [
            {
              location: '/modules',
              name: 'modules'
            }
            // {
            //   location: '/3.22/dojo',
            //   name: 'dojo'
            // },
            // {
            //   location: '/3.22/esri',
            //   name: 'esri'
            // },
          ]
        }
      }
      loadModules(
        [
          'esri/map',
          'modules/WebTiledTDTLayerC',
          'esri/dijit/OverviewMap',
          'esri/layers/WebTiledLayer',
          'esri/layers/ArcGISDynamicMapServiceLayer',
          'esri/SpatialReference',
          'esri/geometry/Extent',
          'esri/geometry/Point',
          'esri/graphic',
          'esri/layers/GraphicsLayer',
          'esri/symbols/PictureMarkerSymbol',
          'esri/tasks/GeometryService',
          'esri/tasks/ProjectParameters',
          'dojo/on',
          'dojo/dom',
          'dojo/domReady!'
        ],
        options
      ).then(
        ([
          Map,
          WebTiledTDTLayer,
          OverviewMap,
          WebTiledLayer,
          ArcGISDynamicMapServiceLayer,
          SpatialReference,
          Extent,
          Point,
          Graphic,
          GraphicsLayer,
          PictureMarkerSymbol,
          GeometryService,
          ProjectParameters,
          on,
          dom
        ]) => {
          this.map = new Map('mapView', {
            logo: false,
            // 经纬度坐标
            center: [120, 29.822],
            zoom: 8
          })
          // 鹰眼支持WebTiledLayer；不支持TiledMapServiceLayer；
          this.myOverviewMap = new OverviewMap({ map: this.map, visible: true })
          this.myOverviewMap.startup()
          this.map.setMapCursor('pointer') //设置鼠标在map上时的样式为手型
          this.putianExtent = new Extent({
            xmin: 118.20304870605469,
            ymin: 24.948190185546878,
            xmax: 119.96086120605469,
            ymax: 25.826409790039065,
            spatialReference: {
              wkid: 4326
            }
          })
          this.map.setExtent(this.putianExtent)
          var layer = new WebTiledTDTLayer('http://${subDomain}.tianditu.gov.cn', { type: 'img' })
          this.map.addLayer(layer)
          var layer_anno = new WebTiledTDTLayer('http://${subDomain}.tianditu.gov.cn', { type: 'cia' })
          this.map.addLayer(layer_anno)
          this.map.on('click', (res) => {
            console.log(this.map.extent)
          })
          //墨卡托投影
          // this.initialExtent = new Extent(
          //   13180709.813449485,
          //   2855211.6152346493,
          //   13227795.02287309,
          //   2875199.898131196,
          //   this.map.spatialReference
          // )
          // this.map.setExtent(this.initialExtent)
        }
      )
    },
    testExcel() {
      //这里可以使用自己的地址
      const options = {
        url: 'https://js.arcgis.com/3.34/',
        dojoConfig: {
          async: true
        }
      }
      loadModules(
        [
          'esri/geometry/Polyline',
          'esri/geometry/Point',
          'esri/graphic',
          'esri/layers/GraphicsLayer',
          'esri/symbols/PictureMarkerSymbol',
          'dojo/on',
          'dojo/dom',
          'dojo/domReady!'
        ],
        options
      ).then(([Polyline, Point, Graphic, GraphicsLayer, PictureMarkerSymbol, on, dom]) => {
        console.log(this.dataSources)
        this.defectLayer = new GraphicsLayer()
        this.importlayer = new GraphicsLayer()
        this.importlayer.clear()
        this.dataSources.map((row) => {
          var line = {
            geometry: { paths: [[row.proj_s, row.proj_e]], spatialReference: this.map.spatialReference },
            symbol: { color: [0, 0, 0, 255], width: 2, type: 'esriSLS', style: 'esriSLSSolid' }
          }
          var g = new Graphic(line)
          this.importlayer.add(g)
          var poi = {
            geometry: { x: row.proj_t[0], y: row.proj_t[1], spatialReference: this.map.spatialReference },
            symbol: {
              color: [255, 0, 0, 128],
              size: 5,
              angle: 0,
              xoffset: 0,
              yoffset: 0,
              type: 'esriSMS',
              style: 'esriSMSCircle',
              outline: { color: [0, 0, 0, 255], width: 1, type: 'esriSLS', style: 'esriSLSSolid' }
            }
          }
          var gPoi = new Graphic(poi)
          this.defectLayer.add(gPoi)
        })
        this.map.addLayer(this.importlayer)
        this.map.addLayer(this.defectLayer)
      })
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
    }
    if (this.basemapGallery) {
      this.basemapGallery.destroy()
    }
    if (this.search) {
      this.search.destroy()
    }
  },
  watch: {
    current(nl) {
      if (nl != 'distance' && this.measurement) {
        this.measurement.hide()
        this.measurement.clearResult()
        this.measurement.setTool('location', false)
        this.measurement.setTool('distance', false)
        this.measurement.setTool('area', false)
      } else {
        if (this.measurement) {
          this.measurement.show()
        }
      }
    },
    dataSources: {
      immediate: false,
      deep: true,
      handler(val) {
        console.log(val, this.dataSources)
        this.testExcel()
      }
    }
  }
}
</script>
<style lang="less" scoped>
@import url('https://js.arcgis.com/3.34/esri/css/esri.css');
.mapList {
  position: absolute;
  right: 10px;
  top: 0;
  z-index: 70;
  background: rgba(48, 65, 86, 0.8);
}
.measure {
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
  width: 220px;
}
#titlePane {
  width: 280px;
}
</style>
<style lang="less">
#mapView {
  height: 100%;
  .esriBasemapGalleryLabelContainer {
    height: 40px !important;
  }
  #myOverviewMapDiv {
    position: absolute;
    right: 35px;
    top: 5px;
    z-index: 998;
    width: 100px;
    height: 100px;
  }
  .arcgisSearch {
    z-index: 20;
    height: 95px;
    width: 400px;
    position: absolute;
    top: 5px;
    left: 50% !important;
    transform: translateX(-50%);
  }

  .esriMeasurementResultValue {
    font-size: 1rem;
  }
  .dijitToggleButtonIconChar,
  .esriMeasurementSeparator,
  .dijitOffScreen {
    display: none;
  }
  .esriMeasurement .dijitContentPane {
    text-align: center;
  }
  .esriPopup .contentPane {
    padding-top: 30px;
    width: 270px;
    text-align: center;
    overflow: hidden;
  }
}
</style>
